package com.ikun.aimian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikun.aimian.common.ErrorCode;
import com.ikun.aimian.exception.ThrowUtils;
import com.ikun.aimian.mapper.AppCommentMapper;
import com.ikun.aimian.model.dto.appcomment.AppCommentQueryRequest;
import com.ikun.aimian.model.entity.AppComment;
import com.ikun.aimian.model.entity.User;
import com.ikun.aimian.model.vo.AppCommentVO;
import com.ikun.aimian.service.AppCommentService;
import com.ikun.aimian.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用评论服务实现
 */
@Service
@Slf4j
public class AppCommentServiceImpl extends ServiceImpl<AppCommentMapper, AppComment> implements AppCommentService {

    @Resource
    private UserService userService;

    @Override
    public void validComment(AppComment comment, boolean add) {
        ThrowUtils.throwIf(comment == null, ErrorCode.PARAMS_ERROR);
        String content = comment.getContent();
        Long appId = comment.getAppId();
        // 新增时必须有评论内容和有效的 appId
        if (add) {
            ThrowUtils.throwIf(StringUtils.isBlank(content), ErrorCode.PARAMS_ERROR, "评论内容不能为空");
            ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR, "应用ID非法");
        }
        // 可以限制评论内容长度
        if (content != null && content.length() > 1024) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "评论内容过长");
        }
    }

    @Override
    public QueryWrapper<AppComment> getQueryWrapper(AppCommentQueryRequest queryRequest) {
        QueryWrapper<AppComment> queryWrapper = new QueryWrapper<>();
        if (queryRequest == null) {
            return queryWrapper;
        }
        if (queryRequest.getAppId() != null) {
            queryWrapper.eq("appId", queryRequest.getAppId());
        }
        if (queryRequest.getUserId() != null) {
            queryWrapper.eq("userId", queryRequest.getUserId());
        }
        if (queryRequest.getStartTime() != null && queryRequest.getEndTime() != null) {
            queryWrapper.between("createTime", queryRequest.getStartTime(), queryRequest.getEndTime());
        }
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();
        if (StringUtils.isNotBlank(sortField)) {
            if ("ascend".equalsIgnoreCase(sortOrder)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByDesc(sortField);
            }
        } else {
            queryWrapper.orderByDesc("createTime");
        }
        return queryWrapper;
    }

    @Override
    public AppCommentVO getCommentVO(AppComment comment, HttpServletRequest request) {
        if (comment == null) {
            return null;
        }
        AppCommentVO vo = AppCommentVO.fromEntity(comment);
        // 查询用户信息，补充 userName
        Long userId = comment.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            if (user != null) {
                vo.setUserName(user.getUserName());
            }
        }
        return vo;
    }

    @Override
    public Page<AppCommentVO> getCommentVOPage(Page<AppComment> commentPage, HttpServletRequest request) {
        List<AppComment> commentList = commentPage.getRecords();
        Page<AppCommentVO> voPage = new Page<>(commentPage.getCurrent(), commentPage.getSize(), commentPage.getTotal());
        if (commentList == null || commentList.isEmpty()) {
            return voPage;
        }
        List<AppCommentVO> voList = commentList.stream()
                .map(comment -> getCommentVO(comment, request))
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }
}
